#!/usr/bin/env python3

import os
import sys
import logging
from logging.handlers import RotatingFileHandler

if not os.path.exists('logs'):
    os.mkdir('logs')

# Log file location
log_name = __name__.split('.')[0] 
logfile = os.path.join('logs', log_name + '.log')

# Gets or creates a logger
# Define your own logger name
logger = logging.getLogger(log_name + "_logger")
# Set default logging level to DEBUG
logger.setLevel(logging.DEBUG)

# create a console handler
# and define a custom log format, set its log level to DEBUG
print_format = logging.Formatter('%(levelname)-8s %(name)-12s %(message)s')
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.DEBUG)
console_handler.setFormatter(print_format)

# create a log file handler
# and define a custom log file format, set its log level to DEBUG

# log_format = logging.Formatter('[%(asctime)s] %(levelname)-8s %(name)-12s %(message)s')
# file_handler = logging.FileHandler(filename=logfile)
# file_handler.setLevel(logging.DEBUG)
# file_handler.setFormatter(log_format)

# create a rotating log file handler
# and define a custom log file format, set its log file level to DEBUG
# the full log file is 2MB, a number of backup is 3 log files
# Don't use two file handler to open the same log file in one py file. otherwise, the second will throw a permission error, when rename the log file
rotating_log_format = logging.Formatter('[%(asctime)s] %(levelname)-8s %(name)-12s %(message)s [in %(pathname)s:%(lineno)d]')
rotating_file_handler = RotatingFileHandler(filename=logfile, maxBytes=10240, backupCount=3)
rotating_file_handler.setLevel(logging.DEBUG)
rotating_file_handler.setFormatter(rotating_log_format)

#Add fille handlers to the logger
logger.addHandler(rotating_file_handler)
logger.addHandler(console_handler)